package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import lombok.SneakyThrows;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {

    private static long tokenExpiration = 600 * 600 * 1000L; // ≈ 166 小时
    private static SecretKey tokenSignKey = Keys.hmacShaKeyFor("M0PKKI6pYGVWWfDZw90a0lTpGYX1d4AQ".getBytes());

    public static String createToken(Long userId, String username) {
        return Jwts.builder()
                .setSubject("USER_INFO")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("userId", userId)
                .claim("username", username)
                .signWith(tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
    }

    public static Claims parseToken(String token) throws ExpiredJwtException, JwtException {
        return Jwts.parserBuilder()
                .setSigningKey(tokenSignKey)
                .setAllowedClockSkewSeconds(60) // ➕ 允许 60 秒时钟偏差
                .build()
                .parseClaimsJws(token)
                .getBody();
    }


}